﻿using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Sustainalytics.Claims;
using Sustainalytics.Entities;
using System;
using System.Collections.Generic;
using System.Configuration.Abstractions;
using System.Linq;
using System.Security.Claims;

namespace Sustainalytics.Auth.Service.GA
{
    public class UserClaimsProvider
    {
        private readonly IAppSettings _appSettings;
        private readonly IOperationClaimsRetriever _claimsRetriever;

        public UserClaimsProvider(IAppSettings appSettings, IOperationClaimsRetriever claimsRetriever)
        {
            _appSettings = appSettings;
            _claimsRetriever = claimsRetriever;
        }

        public IEnumerable<Claim> GetClaims(GaUser user)
        {
            if (user.AccountId == null)
                return Enumerable.Empty<Claim>();

            var userClaims = _claimsRetriever.GetUserClaims(new Account { Name = user.AccountName, Id = user.AccountId.Value }).ToList();

            if (!user.IsFakeIpUser)
                return userClaims;

            var claimsToRemoveForFakeIPUser = _appSettings.AppSetting("ClaimsToRemoveForFakeIPUser")
                .Split(',')
                .Select(s => s.Trim().ToLowerInvariant())
                .ToList();

            return userClaims.Where(claim =>
                !claimsToRemoveForFakeIPUser.Contains(claim.Type.ToLowerInvariant()) ||
                !claim.Value.ToLowerInvariant().StartsWith("allow", StringComparison.Ordinal))
                .ToList();
        }
    }
}
